package com.sl.au.controller;

import com.sl.au.entity.Account;
import com.sl.au.entity.BusinesssellerAuthentication;
import com.sl.au.entity.BusinesssellerBaseInfo;
import com.sl.au.entity.BussinessCheck;
import com.sl.au.entity.BussinessInspection;
import com.sl.au.entity.Evaluate;
import com.sl.au.entity.EventRegister;
import com.sl.au.entity.EventRegisterAndTaskView;
import com.sl.au.entity.EventRegisterTask;
import com.sl.au.entity.Grading;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.GridUserDetails;
import com.sl.au.entity.Module;
import com.sl.au.entity.Option;
import com.sl.au.entity.Part;
import com.sl.au.entity.Hierarchy;
import com.sl.au.entity.PartBaseInfo;
import com.sl.au.entity.PartsType;
import com.sl.au.entity.User;
import com.sl.au.entity.UserTrajectory;
import com.sl.au.entity.UserTrajectoryHistory;
import com.sl.au.entity.ViewForEventRegisterTask;
import com.sl.au.entity.ViewForEventReportTask;
import com.sl.au.service.SectionService;
import com.sl.au.service.UserService;
import com.sl.au.service.UserTrajectoryHistoryService;
import com.sl.au.service.UserTrajectoryService;
import com.sl.utils.ExdeUtil;
import com.sl.utils.MeanGpsUtil;
import com.sl.utils.LngLat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.service.AttachmentService;
import com.sl.au.service.BusinesssellerAuthenticationService;
import com.sl.au.service.BusinesssellerBaseInfoService;
import com.sl.au.service.BussinessCheckService;
import com.sl.au.service.BussinessInspectionService;
import com.sl.au.service.EvaluateService;
import com.sl.au.service.EventRegisterService;
import com.sl.au.service.EventReportService;
import com.sl.au.service.GridAreaInfoService;
import com.sl.au.service.GridUserDetailsService;
import com.sl.au.service.IndexService;
import com.sl.au.service.OptionService;
import com.sl.au.service.PartBaseInfoService;
import com.sl.au.service.PartService;
import com.sl.au.service.PartsTypeService;
import com.sl.au.service.HierarchyService;
import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/ui/userTrajectoryHistory")
public class UserTrajectoryHistoryController extends BaseController {


	@Autowired
	SectionService sectionService;
	@Autowired
	AttachmentService attachmentService;
	@Autowired
	IndexService indexService;
	@Autowired
	UserService userService;
	@Autowired
	PartService	partService;
	@Autowired
	PartBaseInfoService partBaseInfoService;
	@Autowired
	GridAreaInfoService gridAreaInfoService;
	@Autowired
	GridUserDetailsService gridUserDetailsService;
	@Autowired
	EventReportService eventReportService;
	@Autowired
	OptionService optionService;
	@Autowired
	BusinesssellerAuthenticationService businesssellerAuthenticationService;
	@Autowired
	EvaluateService evaluateService;
	@Autowired
	BussinessInspectionService bussinessInspectionService;
	@Autowired
	BussinessCheckService bussinessCheckService;
	@Autowired
	BusinesssellerBaseInfoService businesssellerBaseInfoService;
	@Autowired
	HierarchyService hierarchyService;
	@Autowired
	UserTrajectoryService userTrajectoryService;
	
	@Autowired
	UserTrajectoryHistoryService userTrajectoryHistoryService;
	
	@Autowired
	EventRegisterService eventRegisterService;
	
    
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = createLayoutView("userTrajectoryHistory/userTrajectoryHistoryindex");
		return modelAndView;
	}
	
	@RequestMapping(value="getDeptFollowView/{deptId}", method = RequestMethod.GET)
	public ModelAndView getDeptFollowView(@PathVariable("deptId") String deptId) {
		ModelAndView modelAndView = createLayoutView("index/indexmap");
		modelAndView.setViewName("userTrajectoryHistory/info/QTouchIndexDeptFollow");
		modelAndView.addObject("deptId", deptId);
		return modelAndView;
	}
	
	@RequestMapping(value = "getUserInfoList/{deptId}", method = RequestMethod.GET)
	public Map<String, Object> getUserInfoList(HttpServletRequest request,@PathVariable("deptId") String deptId) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		List<User> users =null;
		int count=0;
		if(org.springframework.util.StringUtils.hasText(deptId)&&!deptId.equals("all"))
		{
			users=userService.getUsersByDept(start, length, key, deptId, null, null);
			count=userService.getCountByDept(deptId, key);
		}else if(deptId.equals("all")){
			if (org.springframework.util.StringUtils.hasText(key)){
				users=userService.getUsers(start, length, key, null, null);		
			}else {
				users=userService.getPage(start, length, null, null, null);			
			}
			count=userService.getCount(key);
		}
		
		map.put("data", users);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	@RequestMapping(value="getUserListByIds/{ids}", method = RequestMethod.POST)
	public Map<String,Object> getUserListByIds(@PathVariable("ids") String ids,@RequestBody Map<String,Object> json) {
		Map<String,Object> map = new HashMap<String,Object>();
		String[] list=ids.split(",");
		List<String> idsList = new ArrayList();
		Map<String, List<UserTrajectoryHistory>> tempTrajectory =  new HashMap<String, List<UserTrajectoryHistory>>();
		
		String cyc = (String) json.get("cyc");
		String begin = (String) json.get("beginDate");
		String end = (String) json.get("endDate");
		
		Date beginDate = null;
		Date endDate = null;
		if(cyc.equals("week")) {
			beginDate = ExdeUtil.getThisWeekBegin();
			endDate = ExdeUtil.getThisWeekEnd();
		}else if(cyc.equals("month")) {
			beginDate = ExdeUtil.getThisMonthBegin();
			endDate = ExdeUtil.getThisMonthEnd();
		}else if(cyc.equals("year")) {
			beginDate = ExdeUtil.getThisYearBegin();
			endDate = ExdeUtil.getThisYearEnd();
		}else {
			String pattern = "yyyy-MM-dd HH:mm:ss";
			begin += " 00:00:00";
			end += " 23:59:59";
			beginDate = ExdeUtil.str2Date(begin, pattern);
			endDate = ExdeUtil.str2Date(end, pattern);
			
		}
		
		
		Map<String, User> tempUser =  new HashMap<String, User>();
		for(int i=0;i<list.length;i++)
		{
			idsList.add(list[i]);
			List<UserTrajectoryHistory> tempLine = new ArrayList<UserTrajectoryHistory>();
			tempTrajectory.put(list[i], tempLine);
			tempUser.put(list[i], null);
		}
		List<UserTrajectoryHistory> users =this.userTrajectoryHistoryService.getRepository().getAllByUserIdsAndDate(idsList,beginDate,endDate);
		for(UserTrajectoryHistory ut: users) {
			User u = ut.getUser();
			String uId = u.getId();
			tempTrajectory.get(uId).add(ut);
			if(tempUser.get(uId) == null) {
				tempUser.put(uId, u);
			}
		}
		List<UserTrajectoryHistory> users2 = new ArrayList<UserTrajectoryHistory>();
		
		for(int i=0;i<list.length;i++){
			List<UserTrajectoryHistory> mUsers = tempTrajectory.get(list[i]);
			User mUser = tempUser.get(list[i]);
			ArrayList<LngLat> mLine = new ArrayList<LngLat>();
			Date lDate = null;
			for(int j=0;j<mUsers.size();j++) {
				Date tDate = mUsers.get(j).getTrajectoryTime();
				if(lDate != null && tDate.getTime() - lDate.getTime() >= 1000 * 60 * 5) {
					setUserTrajectory(users2,mLine,mUser);
					mLine.clear();
				}
				lDate = tDate;
				LngLat p = new LngLat(mUsers.get(j).getLongitude(), mUsers.get(j).getLatitude());
				mLine.add(p);
			}
			setUserTrajectory(users2,mLine,mUser);
		}
		
		map.put("users", users2);
		return map;
	}
	
	public void setUserTrajectory(List<UserTrajectoryHistory> users,ArrayList<LngLat> mLine,User mUser) {
		ArrayList<LngLat> gLine = new ArrayList<LngLat>();
		if(mLine.size() > 100) {
			MeanGpsUtil gpsUtil = new MeanGpsUtil(mLine);
			gLine = gpsUtil.meangps();
		}else {
			gLine.addAll(mLine);
		}
		
		for(int k=0;k<gLine.size();k++) {
			UserTrajectoryHistory ut = new UserTrajectoryHistory();
			ut.setPointIndex(k);
			ut.setUser(mUser);
			ut.setLatitude(gLine.get(k).latitude);
			ut.setLongitude(gLine.get(k).longitude);
			users.add(ut);
		}
	}
	
	@RequestMapping(value="getUserList/{deptId}", method = RequestMethod.GET)
	public Map<String,Object> getUserList(@PathVariable("deptId") String deptId) {
		Map<String,Object> map = new HashMap<String,Object>();
		Hierarchy dept =this.hierarchyService.getRepository().findOne(deptId);
		List<UserTrajectory> users =this.userTrajectoryService.getRepository().getAllByDept(dept);
		map.put("users", users);
		return map;
	}
	
	@RequestMapping(value="getEventFollowView", method = RequestMethod.GET)
	public ModelAndView getEventFollowView() {
		ModelAndView modelAndView = createLayoutView("index/indexmap");
		modelAndView.setViewName("userTrajectoryHistory/info/QTouchIndexEventFollow");
		return modelAndView;
	}
	
	@RequestMapping(value = "getEventInfoList", method = RequestMethod.GET)
	public Map<String, Object> getpage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		Option opt = optionService.getRepository().findByTitleAndGroup("已完结", "内部事件流转状态");
		String type = "";
		if(opt != null) {
			type = opt.getId();
		}
		List<ViewForEventRegisterTask> rvs = null;
		int count=0;
		
		count = this.eventRegisterService.getCountByTaskStateAndOperateUser(type,"",key);
		rvs=eventRegisterService.getPageByTaskStateAndOperate(start,length,type,"",key,"registerEventAccTime", Sort.Direction.DESC);
		
		map.put("data", rvs);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	@RequestMapping(value="getEventUserListById/{registid}/{id}", method = RequestMethod.GET)
	public Map<String,Object> getEventUserListByIds(@PathVariable("id") String id,@PathVariable("registid") String registid) {
		Map<String,Object> map = new HashMap<String,Object>();
		
		Option opt1 = optionService.getRepository().findByTitleAndGroup("处理中", "内部事件流转状态");
		Option opt2 = optionService.getRepository().findByTitleAndGroup("已完结", "内部事件流转状态");
		
		ViewForEventRegisterTask task1 = eventRegisterService.getEventRegisterTaskByOpt(opt1.getId(), registid);
		ViewForEventRegisterTask task2 = eventRegisterService.getEventRegisterTaskByOpt(opt2.getId(), registid);
		
		Date beginDate = task1.getEventTaskTime();
		Date endDate = task2.getEventTaskTime();
		
		List<UserTrajectoryHistory> user =this.userTrajectoryHistoryService.getRepository().getUserByIdAndDate(id, beginDate,endDate);
		map.put("users", user);
		return map;
	}
	
}
